import loadHighlightText from "~api/highlightText/load";
const MAX_RETRY_TIME = 2500; // Stop trying to highlight after this time (in ms)
const RETRY_INTERVAL = 500;
const lostHighlights = new Map();

const addHighlightError = (highlight, highlightIndex) => {
  const highlightError = {
    highlight,
    highlightIndex,
    errorTime: Date.now(),
  };
  highlightError.timeout = setTimeout(retryHighlightError, RETRY_INTERVAL, highlightError);
  lostHighlights.set(highlightIndex, highlight);
}

const retryHighlightError = (highlightError) => {
  const success = loadHighlightText(highlightError.highlight, highlightError.highlightIndex, true);

  if (success) {
    lostHighlights.delete(highlightError.highlightIndex);
    return;
  }

  if (Date.now() - highlightError.errorTime < MAX_RETRY_TIME) {
    highlightError.timeout = setTimeout(retryHighlightError, RETRY_INTERVAL, highlightError);
  }
}

const getLostHighlights = () => {
  return lostHighlights;
}

const removeLostHighlight = (highlightIndex) => {
  const highlightError = lostHighlights.get(highlightIndex);
  clearTimeout(highlightError?.timeout);
  lostHighlights.delete(highlightIndex);
}

export { addHighlightError, getLostHighlights, removeLostHighlight };
